package com.longrise.filedownloader;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.text.TextUtils;


/**
 * Created by callxkj on 16/5/11.
 * 服务可用绑定也可也不绑定
 */
public class DownloadService extends Service {

    private static final String TAG = "DownloadService";

    private static DownloadManager mDownloadManager;

    private static boolean isChangeManager = false;

    private static boolean isCanGetManage= false; //保证用户id的方法必须调用

    private DownloadBind mBind = new DownloadBind();

    private static String mUserid;

    /**
     * 设置用户id
     * @param userid 用户id 可以为null 但必须调用
     */
    public static void setUserid(String userid) {
        if ((!TextUtils.isEmpty(mUserid)) && (!mUserid.equals(userid))) {
            isChangeManager = true;
        }
        mUserid = userid;
        isCanGetManage = true;
    }

    public static DownloadManager getDownloadManager() {
        return mDownloadManager;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        if(isCanGetManage){
            mDownloadManager = new DownloadManager(DownloadService.this, mUserid);
            isCanGetManage = false;
        }

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(isCanGetManage){
            if (mDownloadManager == null || isChangeManager) {
                mDownloadManager = new DownloadManager(DownloadService.this, mUserid);
                isChangeManager = false;
                isCanGetManage = false;
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }


    @Override
    public IBinder onBind(Intent intent) {
        return mBind;
    }

    public class DownloadBind extends Binder implements IdownloadService {

        @Override
        public DownloadManager getDownloadManager(Context context, String userid) {
            if (mDownloadManager == null) {
                synchronized (DownloadService.class) {
                    if (mDownloadManager == null) {
                        mDownloadManager = new DownloadManager(context, userid);
                    }
                }
            }
            return mDownloadManager;
        }
    }
}
